<template>
    <Header /> <!-- 包含头部组件 -->
    <Menu /> <!-- 包含菜单组件 -->
<div class="container-fluid userinfo" v-if="userInfo">
  <div class="row">
    <div class="col-2"><img class="useravatar" :src="avatarImg"></div>
    <div class="col textinfo">
      <div class="row nickname">
            {{ userInfo.nickname }}
      </div>
      <div class="row introduce">
        介绍：{{ userInfo.introduce }}
      </div>
    </div>
  </div>

  <div class="row text-center usermenudiv">
    <div class="col" @click="goToWriter">
      <div class="row justify-content-center">
        <img class="usermenu" src="@/assets/icon/writer.png">
      </div>
      <div class="row justify-content-center">
        发布小说
      </div>
    </div>
    <div class="col" @click="dialogFormVisible = true">
      <div class="row justify-content-center">
        <img class="usermenu" src="@/assets/icon/update.png">
      </div>
      <div class="row justify-content-center">
        更新信息
      </div>
    </div>
    <div class="col" @click="logout">
      <div class="row justify-content-center">
        <img class="usermenu" src="@/assets/icon/logout.png">
      </div>
      <div class="row justify-content-center">
        退出登录
      </div>
    </div>
  </div>

  <!-- 小说信息 -->
  <div class="row justify-content-center mt-4 fabudiv">
    <div class="col fabutitle">我发布的书籍</div>
    <div class="row justify-content-center text-center">
      <div v-for="novel in novelInfo" :key="novel.novel_id" class="col-6 bookrow">
      <div class="row justify-content-center">
        <img @click="goToRead(novel.novel_id)" :src="novel.novel_pic" class="card-img-top" :alt="novel.novel_name" style="width: 140px;height: 150px"/>
      </div>
        <div class="row justify-content-center text-center noveltitle">
          {{ truncate(novel.novel_name) }}
        </div>
        <div class="row justify-content-center">
          <button class="editbtn" @click="editNovel(novel.novel_id)">编辑书籍</button>
        </div>
        <div class="row justify-content-center">
          <button class="editbtn" @click="editChapter(novel.novel_id)">编辑章节</button>
        </div>

      </div>
    </div>
  </div>



</div>
<div v-else class="container-fluid">加载中...</div>
  <!-- 编辑用户信息的弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="更新个人资料" width="90%">
    <el-form :model="form">
      <el-form-item label="登录账号：">
        <el-input v-model="form.username" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="用户昵称：">
        <el-input v-model="form.nickname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户介绍：">
        <el-input v-model="form.introduce" autocomplete="off" />
      </el-form-item>
      <el-form-item label="登录密码：">
        <el-input v-model="form.password" placeholder="不修改就留空" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUserInfo">
          更新
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive,ref, onMounted } from 'vue';
import axios from 'axios';
import VueCookies from 'vue-cookies';
import Header from "@/components/Header.vue";
import Menu from "@/components/Menu.vue";
import { ElNotification } from "element-plus";
import router from "@/router";
import config from "../../../config/config.js";

// 状态变量
const loading = ref(true); // 加载状态
const userInfo = ref(null); // 用户信息
const novelInfo = ref([]); // 小说信息
const avatarImg = ref(`${config.apiUrl}/uploads/default-avatar.jpg`);
let novelId = null;
//dialog
const dialogFormVisible = ref(false)
// 对话框的可见性
const form = reactive({
  nickname: '',
  introduce: '',
  username: '',
  password: '',
})
// 打开对话框
const editNovel = (funcnoveild) => {
  router.push('/edit/novel/'+funcnoveild);
};
const editChapter = (funcnoveild) => {
  router.push('/edit/chapterlist/'+funcnoveild);
};
// 保存用户信息
const saveUserInfo = async () => {
  const userToken = VueCookies.get('userToken');
  if (!userToken) {
    ElNotification({
      message: 'userToken为空，请重新登录！',
      type: 'error',
      duration: 1000
    });
    router.push('/user/login');
    return;
  }

  const requestBody = {
    nickname: form.nickname,
    introduce: form.introduce,
    password: form.password,
  };

  if (form.password && form.password.trim() !== '') {
    if(form.password.length<6){
      ElNotification({
        message: '修改的密码不得少于六位！',
        type: 'error',
        duration: 2000
      });
      return;
    }
  }

  try {
    await axios.post(`${config.apiUrl}/user/update`, requestBody, {
      headers: {
        'Authorization': `Bearer ${userToken}`,
        'Content-Type': 'application/json'
      },
    });

    // 更新用户信息并关闭弹窗
    userInfo.value = { ...requestBody }; // 解构并更新用户信息
    dialogFormVisible.value = false; // 关闭弹窗

    ElNotification({
      message: '用户信息更新成功！',
      type: 'success',
      duration: 1000
    });

  } catch (error) {
    ElNotification({
      message: '用户信息更新失败！',
      type: 'error',
      duration: 1000
    });
  }
};
// 从服务器获取用户和小说信息
const fetchUserAndNovelInfo = async () => {
  const userToken = VueCookies.get('userToken');
  if (!userToken) {
    ElNotification({
      message: 'userToken 不存在，请重新登录',
      type: 'error',
      duration: 1000
    });
    router.push('/user/login');
    return;
  }

  try {
    const response = await axios.get(`${config.apiUrl}/user/info`, {
      headers: {
        'Authorization': `Bearer ${userToken}` // 使用 Cookie 中的 Token
      },
    });

    const data = response.data;
    userInfo.value = data.userInfo; // 获取用户信息
    novelInfo.value = data.novelInfo; // 获取小说信息
    form.nickname = userInfo.value.nickname;
    form.username = userInfo.value.username;
    form.introduce = userInfo.value.introduce;
  } catch (error) {
    ElNotification({
      message: '获取用户和小说信息失败',
      type: 'error',
      duration: 1000
    });
    VueCookies.set('userToken', ''); // 清除cookie
    router.push('/user/login'); // 失败时跳转到登录页面
  } finally {
    loading.value = false; // 加载结束
  }
};
// 退出登录
const logout = () => {
  VueCookies.remove('userToken'); // 删除 userToken
  ElNotification({
    message: '退出登录成功！',
    type: 'success',
    duration: 1000
  });
  router.push('/user/login'); // 重定向到登录页面
};
// 作家中心
const goToWriter = () => {
  router.push('/writer'); // 重定向到登录页面
};
const goToRead = (novelid) => {
  router.push('/novel/'+novelid); // 重定向到登录页面
};
const truncate = (text) => {
  if (!text) return '';
  return text.length > 12 ? text.substring(0, 12) + '...' : text;
};
// 初始化时获取用户和小说信息
onMounted(fetchUserAndNovelInfo);
</script>

<style scoped>
.useravatar{
  width: 50px;
  border-radius: 50%;
}
.textinfo{
  padding: 3px 20px;
  font-size: 17px;
}
.nickname{
  font-weight: bold;
}
.useravatar{
  margin-top: 6px;
}
.userinfo{
  padding:20px;
}
.usermenu{
  width: 45px;
}
.usermenudiv{
  padding: 30px;
  margin-top: 29px;
  box-shadow:0px 0px 80px rgba(0, 0, 0, 0.05);
  border-radius: 10px;
}
.introduce{
  padding-top: 9px;
  font-size: 13px;
}
.editbtn{
  border: 1px solid black;
  margin: 10px;
  padding: 3px;
  width: 70%;
  border-radius: 4px;
  background-color: white;
  letter-spacing: 2px;
}
.bookrow{
  padding: 12px;
}
.fabutitle{
  font-size: 19px;
  font-weight: bold;
}
.fabudiv{
  box-shadow:0px 0px 80px rgba(0, 0, 0, 0.05);
  padding: 10px;
  border-radius: 10px;
}
.noveltitle{
  padding-top: 13px;
}
</style>
